package com.agileboot.domain.system.dict;


import cn.hutool.log.Log;
import com.agileboot.common.core.page.PageDTO;
import com.agileboot.common.exception.ApiException;
import com.agileboot.common.exception.error.ErrorCode;
import com.agileboot.domain.system.dict.command.DictTypeAddCommand;
import com.agileboot.domain.system.dict.command.DictTypeUpdateCommand;
import com.agileboot.domain.system.dict.db.SysDictTypeEntity;
import com.agileboot.domain.system.dict.db.SysDictTypeService;
import com.agileboot.domain.system.dict.dto.DictTypeDTO;
import com.agileboot.domain.system.dict.model.DictTypeModel;
import com.agileboot.domain.system.dict.model.DictTypeModelFactory;
import com.agileboot.domain.system.dict.query.DictTypeQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class DictApplicationService {

    private final SysDictTypeService dictTypeService;

    private final DictTypeModelFactory dictTypeModelFactory;

    public PageDTO<DictTypeDTO> getDictTypeList(DictTypeQuery query) {
        Page<SysDictTypeEntity> page = dictTypeService.page(query.toPage(), query.toQueryWrapper());
        List<DictTypeDTO> records = page.getRecords().stream().map(DictTypeDTO::new).collect(Collectors.toList());
        return new PageDTO<>(records, page.getTotal());
    }

    public void addDictType(DictTypeAddCommand command){
        DictTypeModel dictTypeModel = dictTypeModelFactory.create();
        dictTypeModel.loadDictTypeAdd(command);

        dictTypeModel.checkDictTypeIsUnique();
        dictTypeModel.checkDictNameIsUnique();

        dictTypeModel.insert();
    }

    public void updateDictType(DictTypeUpdateCommand command){
        DictTypeModel dictTypeModel = dictTypeModelFactory.loadById(command.getDictId());
        dictTypeModel.loadDictTypeUpdate(command);

        dictTypeModel.checkDictNameIsUnique();
        dictTypeModel.checkDictTypeIsUnique();

        dictTypeModel.updateById();
    }

    public void deleteDictType(Long dictId,String dictType){
        int count = dictTypeService.checkDictDataExists(dictType);
        if(count>0){
            throw new ApiException(ErrorCode.Business.DICT_TYPE_HAVE_DATA);
        }
        dictTypeService.removeById(dictId);
    }


}
